package com.shushan.util;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shushan.base.Constants;
import com.shushan.home.bean.AppDialogBean;
import com.shushan.mixedexam.bean.MutiExerciseBean;
import com.shushan.pages.newtype.bean.NewWordBean;
import com.shushan.ui.RoundProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @ClassName: DownloadUtil
 * @Desciption: //下载工具类
 * @author: zhangshihao
 * @date: 2018-07-23
 */
public class DownloadUtil {

    private static final String TAG = DownloadUtil.class.getSimpleName();
    public static final int FILENAME_INDEX = 0;
    public static final int DOWNLOAD_URL_INDEX = 1;
    public static final int TYPE_AUDIO = 1;
    public static final int TYPE_GIF = 2;
    private static final String AUDIO_FILE_POSTFIX = ".mp3";
    private static final String GIF_FILE_POSTFIX = ".gif";

    private RoundProgressBar downloadProgressBar;
    private static DownloadUtil downloadUtil;
    private OnDownloadFinishedListener onDownloadFinishedListener;
    private OnSourceExistListener onSourceExistListener;

    public static DownloadUtil getInstance() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    @SuppressLint("StaticFieldLeak")
    public void downloadData(final Context context, List<String[]> downloadInfos) {
        if (ToolUtils.isListEmpty(downloadInfos)) {
            return;
        }
        boolean allExist = true;
        for (int i = 0; i < downloadInfos.size(); i++) {
            File file = new File(downloadInfos.get(i)[FILENAME_INDEX]);
            if (!file.exists()) {
                allExist = false;
            }
        }
        if (allExist) {
            if (onSourceExistListener != null) {
                onSourceExistListener.onSourceExist();
            }
            Toast.makeText(context, "资源已存在，开始学习吧", Toast.LENGTH_SHORT).show();
            return;
        }
        new MyAsynTask(context).execute(downloadInfos);
    }


    @SuppressLint("StaticFieldLeak")
    private class MyAsynTask extends AsyncTask<List<String[]>, Double, Boolean> {

        Context mContext;

        MyAsynTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
            downloadProgressBar = DialogUtil.showDownloadProgressDialog(mContext);
        }

        @SafeVarargs
        @Override
        protected final Boolean doInBackground(List<String[]>... params) {
            Log.i(TAG, "doInBackground");
            List<String[]> infos = params[0];
            FileOutputStream fos = null;
            InputStream in = null;
            Log.i(TAG, "infos:" + new Gson().toJson(infos));
            for (int i = 0; i < infos.size(); i++) {
                String[] info = infos.get(i);
                //@{跳过已存在的文件
                File tempFile = new File(info[FILENAME_INDEX]);
                if (tempFile.exists()) {
                    continue;
                }
                //@}
                HttpURLConnection conn = null;
                try {
                    Log.i(TAG, "----:" + info[DOWNLOAD_URL_INDEX]);
                    URL url = new URL(info[DOWNLOAD_URL_INDEX]);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10000);
                    conn.setReadTimeout(30000);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                File file = new File(info[FILENAME_INDEX]);

                try {
                    in = conn.getInputStream();
                    if (in == null)
                        return false;
                    //如果文件已经存在，并且第二个参数为true，则向原先的文件追加数据，否则重新写。
                    fos = new FileOutputStream(file, false);
                    byte[] buffer = new byte[4 * 1024];
                    int len = 0;
                    while ((len = in.read(buffer)) != -1) {
                        //更新进度
                        fos.write(buffer, 0, len);
                    }
                    Log.i(TAG, "infos:" + infos.size());
                    publishProgress((double) i, (double) infos.size());
                    fos.flush();
                    in.close();
                    fos.close();
                } catch (Exception e) {
                    Log.i(TAG, "e:" + e.toString());
                    if (file.exists())
                        file.delete();
                    e.printStackTrace();
                    return false;
                } finally {
                    conn.disconnect();
                }
            }
            return true;
        }

        @Override
        protected void onProgressUpdate(Double... values) {
            super.onProgressUpdate(values);
            if (downloadProgressBar != null) {
                downloadProgressBar.setProgress((int) ((values[0] / values[1]) * 100));
            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
//            Log.i(TAG, "onPostExecute : " + aBoolean);
            DialogUtil.dismissDownloadDialog(mContext);
            if (aBoolean) {
                ToastUtils.showToast(mContext, "资源下载完成");
            } else {
                ToastUtils.showToast(mContext, "资源下载出现错误，请检查网络后重试");
            }
            if (onDownloadFinishedListener != null) {
                onDownloadFinishedListener.onDownloadFinished();
            }
        }
    }

    ;


    public void createStrangeWordsDownloadDir() {
        createExamRootDir();
        File file2 = new File(Constants.STRANGE_WORDS_DOWNLOAD_FOLDER);
        if (!file2.exists()) {
            file2.mkdir();
        }
    }

    public void createEnglishWordsDownloadDir() {
        createExamRootDir();
        File file2 = new File(Constants.ENGLISH_WORDS_DOWNLOAD_FOLDER);
        if (!file2.exists()) {
            file2.mkdir();
        }
    }

    public void createSpeakingExamDownloadDir() {
        createExamRootDir();
        File file2 = new File(Constants.SPEAKING_EXAM_DOWNLOAD_FOLDER);
        if (!file2.exists()) {
            file2.mkdir();
        }
    }

    public void createHearingExamDownloadDir() {
        createExamRootDir();
        File file2 = new File(Constants.HEARING_EXAM_DOWNLOAD_FOLDER);
        if (!file2.exists()) {
            file2.mkdir();
        }
    }

    public void createExamRootDir() {
        File file3 = new File(Constants.DOWNLOAD_FOLDER);
        if (!file3.exists()) {
            file3.mkdir();
        }
        File file1 = new File(Constants.EXAM_DATA_DOWNLOAD_FOLDER);
        if (!file1.exists()) {
            file1.mkdir();
        }
    }

    public void createAllTypeExamDownloadDir() {
        createHearingExamDownloadDir();
        createSpeakingExamDownloadDir();
        createEnglishWordsDownloadDir();
        createStrangeWordsDownloadDir();
    }

    public static String getStrangeWordsStudyAudioPath(NewWordBean newWordBean, int outlineDetailId, int index, int resType) {
        StringBuffer sb = new StringBuffer();
        sb.append(Constants.STRANGE_WORDS_DOWNLOAD_FOLDER)
                .append(outlineDetailId + "")
                .append(newWordBean.id + "");
        if (resType == TYPE_AUDIO) {
            sb.append(index + "")
                    .append(AUDIO_FILE_POSTFIX);
        } else {
            sb.append(GIF_FILE_POSTFIX);
        }
        return sb.toString();
    }

    public static String getStrangeWordsExamAudioPath(MutiExerciseBean exerciseBean) {
        StringBuffer sb = new StringBuffer();
        sb.append(Constants.STRANGE_WORDS_DOWNLOAD_FOLDER)
                .append(exerciseBean.outline_detail_id + "")
                .append(exerciseBean.id + "")
                .append(AUDIO_FILE_POSTFIX);
        return sb.toString();
    }

    public static String getEnglishWordsStudyAudioPath(int outlineDetailId, int id) {
        StringBuffer sb = new StringBuffer();
        sb.append(Constants.ENGLISH_WORDS_DOWNLOAD_FOLDER)
                .append(outlineDetailId)
                .append(id)
                .append(AUDIO_FILE_POSTFIX);
        return sb.toString();
    }

    public static String getSpeakingExamAudioPath(int outlineDetailId, int id) {
        StringBuffer sb = new StringBuffer();
        sb.append(Constants.SPEAKING_EXAM_DOWNLOAD_FOLDER)
                .append(outlineDetailId)
                .append(id)
                .append(AUDIO_FILE_POSTFIX);
        return sb.toString();
    }

    public static String getHearingExamAudioPath(int outlineDetailId, int id) {
        StringBuffer sb = new StringBuffer();
        sb.append(Constants.HEARING_EXAM_DOWNLOAD_FOLDER)
                .append(outlineDetailId)
                .append(id)
                .append(AUDIO_FILE_POSTFIX);
        return sb.toString();
    }

    public void setOnDownloadFinishedListener(OnDownloadFinishedListener onDownloadFinishedListener) {
        this.onDownloadFinishedListener = onDownloadFinishedListener;
    }

    public void setOnSourceExistListener(OnSourceExistListener onSourceExistListener) {
        this.onSourceExistListener = onSourceExistListener;
    }

    public interface OnDownloadFinishedListener {
        void onDownloadFinished();
    }

    public interface OnSourceExistListener {
        void onSourceExist();
    }

    public static void createNomedia() {
        File nomedia = new File(Constants.DOWNLOAD_FOLDER + ".nomedia");
        File fileParent = nomedia.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }

        if (!nomedia.exists())
            try {
                nomedia.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    public static boolean fileIsExists(String strFile) {
        if (TextUtils.isEmpty(strFile)) {
            return false;
        }

        try {
            File file = new File(strFile);
            if (file.exists()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }

    public static boolean advertIsExists(int id) {
        if (id <= 0) {
            return false;
        }

        createNomedia();

        return fileIsExists(Constants.ADVERT_DOWNLOAD_FOLDER + id + ".png");
    }

    public static void downloadAdvertImg(Context context, AppDialogBean appDialogBean) {
        if (appDialogBean == null) {
            return;
        }

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(appDialogBean.pic))
                .setDestinationUri(Uri.fromFile(new File(Constants.ADVERT_DOWNLOAD_FOLDER + appDialogBean.id + ".png")))//设置文件存放目录
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
                .setVisibleInDownloadsUi(false);

        DownloadManager downManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        downManager.enqueue(request);
    }
}
